package impl

import (
	"context"

	"gitee.com/go-course/go8/projects/devcloud/cmdb/apps/resource"
)

func (s *service) save(ctx context.Context, res *resource.Resource) (err error) {
	tx := s.db.WithContext(ctx).Begin()
	defer func() {
		if err != nil {
			tx.Rollback()
			return
		}
		err := tx.Commit().Error
		if err != nil {
			s.log.Errorf("commit error, %s", err)
		}
	}()

	rid := &ResourceId{ResourceId: res.Meta.ResourceId}
	err = tx.Create(res.Meta).Error
	if err != nil {
		return
	}
	err = tx.Create(&Spec{Spec: res.Spec, ResourceId: rid}).Error
	if err != nil {
		return
	}
	err = tx.Create(&Status{Status: res.Status, ResourceId: rid}).Error
	if err != nil {
		return
	}
	err = tx.Create(&Cost{Cost: res.Cost, ResourceId: rid}).Error
	if err != nil {
		return
	}

	err = tx.Where("resource_id = ?", res.Meta.ResourceId).Delete(&Tag{}).Error
	if err != nil {
		return
	}
	for i := range res.Tags {
		err = tx.Create(&Tag{Tag: res.Tags[i], ResourceId: rid}).Error
		if err != nil {
			return
		}
	}

	return
}
